package org.pearl.boot.mybatis.demo.plugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * Created by TD on 2021/6/9
 */
@Component
/**
 * @Intercepts 拦截哪些  type四大对象 ，method 那个方法，args 方法的参数  因为有重载
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ExamplePlugin implements Interceptor {


    private Properties properties = new Properties();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // do something ...... 方法拦截前执行代码块
        System.out.println("ExamplePlugin do something ...... 方法拦截前执行代码块");
        Object result = invocation.proceed();
        // do something .......方法拦截后执行代码块
        System.out.println(" ExamplePlugin do something .......方法拦截后执行代码块");
        return result;
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    /**
     * 生成动态代理对象，可以使用MyBatis提 供的Plugin类的wrap方法, 也可以自定义
     *
     * @param target 目标对象，MyBatis四大组件
     * @return 代理对象
     */
    @Override
    public Object plugin(Object target) {
        // MyBatis提供的Plugin类的wrap方法
        return Plugin.wrap(target, this);
    }
}